// CheckAuth();
// 版本数据
let versions = [];
// 响应式数据
const loading = false
const searchKey = ''
const currentPage = 1
const pageSize = 10
const total = 0
// 加载数据方法
const loadData = async () => {
    try {
        //loading.value = true
        const params = {
            page: currentPage.value,
            pageSize: pageSize.value,
            search: searchKey.value
        }

        // 获取认证信息（根据实际存储方式调整）
        const token = localStorage.getItem('authToken');
        if (!token) AuthReDirection(false);

        const response = await fetch(`/api/mashine/list?${new URLSearchParams(params)}`, {
            method: 'GET',
            headers: new Headers({
                'Authorization': `${token}`
            }),
        });
        if (!response.ok) {
            if (response.status == 401) {
                AuthReDirection(false);
            }
            else if(response.status == 402){
                const data = await response.json();
                AuthPermissionErr(data.error);
            }
            else {
                throw new Error('数据加载失败')
            }
        }

        const { data, total } = await response.json()

        if (data && total > 0) {
            versions.value = data.map(item => {
                // 添加逻辑：判断是否重要版本
                const date = new Date(item.CreatedAt)
                const localTime = `${date.getFullYear()}年${(date.getMonth() + 1).toString().padStart(2, '0')}月${date.getDate().toString().padStart(2, '0')}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;

                return {
                    ...item,
                    CreatedAt: localTime,
                    remark: (item.description || '').replace(/\n/g, '\n')
                }
            })
        }
    } catch(err){
        console.log(err)
    }  finally {

    }
}

// 渲染版本列表
async function renderVersionList() {
    try {
        await loadData(); // 等待数据加载完成

        const tbody = document.getElementById('version-list');
        tbody.innerHTML = '';

        if (versions.value) {
            // 确保访问 versions.value（假设 versions 是 ref/reactive 对象）
            versions.value.forEach((item, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                <td>${item.name}</td>
                <td>${item.code}</td>
                <td>${item.createdAt}</td>
                <td>${item.creator}</td>
            `;
                row.dataset.index = index;
                tbody.appendChild(row);
            });


        }
    } catch (error) {
        console.error('渲染失败:', error);
    }
}


// 获取DOM元素
const createBtn = document.getElementById('create-version');
const createModal = document.getElementById('create-modal');
const closeBtn = document.getElementById('close-create-modal');
const cancelBtns = document.getElementsByClassName('cancel-btn');
const versionForm = document.getElementById('work-tagert-form');

// 创建新版本
document.getElementById('create-version').addEventListener('click', () => {
    // renderVersionList();
    createModal.style.display = 'flex';
    versionForm.reset(); // 清空表单历史数据
});

// 关闭弹窗的通用方法
function closeModal() {
    createModal.style.display = 'none';
}

// 绑定关闭事件
closeBtn.addEventListener('click', closeModal);
Array.from(cancelBtns).forEach(btn => {
    btn.addEventListener('click', closeModal);
});

// 表单提交处理
versionForm.addEventListener('submit',  (e) => {
    e.preventDefault();

    // 收集表单数据
    const machineData = {
        name: document.getElementById('input-name').value,
        description: document.getElementById('input-remark').value,
    };

    // 获取认证信息（根据实际存储方式调整）
    const token = localStorage.getItem('authToken');
    if (!token) AuthReDirection(false);

    // 发送POST请求
    fetch('/api/mashine/create', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `${token}`,
        },
        body: JSON.stringify(machineData)
    })
        .then(async response => {
            if (!response.ok) {
                if (response.status == 401) {
                    AuthReDirection(false);
                }
                else if(response.status == 402){
                    const data = await response.json();
                    AuthPermissionErr(data.error);
                }
                else {
                    throw new Error('状态码异常: ' + response.status);
                }

            }         
        })
        .then(data => {
            console.log('创建成功:', data);
            closeModal();
            renderVersionList();
            // 此处可添加表格数据刷新逻辑
        })
        .catch(error => {
            console.error('请求失败:', error);
            alert('创建失败，请检查控制台');
        });

});

// 页面切换功能
function switchPage(pageId) {
    document.querySelectorAll('.page-container').forEach(page => {
        page.classList.remove('active');
    });
    const targetPage = document.getElementById(`${pageId}-page`);
    if (targetPage) targetPage.classList.add('active');
}

// 导航栏交互
document.querySelectorAll('.nav-button').forEach(button => {
    button.addEventListener('click', function (e) {
        e.preventDefault();
        document.querySelectorAll('.nav-button').forEach(btn => btn.classList.remove('active'));
        this.classList.add('active');
        const pageId = this.getAttribute('href').substring(1);
        switchPage(pageId);
        window.location.hash = pageId;
    });
});

// 版本详情弹窗
function showVersionDetail(versionData) {
    const detailContainer = document.getElementById('version-detail');
    detailContainer.innerHTML = `
        <div class="detail-item" data-id="${versionData.id}">
            <label>工作台名称</label>
            <p>${versionData.name}</p>
        </div>
        <div class="detail-item">
            <label>编号</label>
            <p>${versionData.code}</p>
        </div>
        <div class="detail-item">
            <label>创建时间</label>
            <p>${versionData.createdAt}</p>
        </div>
        <div class="detail-item">
            <label>创建人</label>
            <p>${versionData.creator}</p>
        </div>
        <div class="detail-item">
            <label>说明</label>
            <p>${versionData.remark.replace(/\n/g, '<br>')}</p>
        </div>
    `;
    document.getElementById('version-modal').style.display = 'flex';
}

// 表格点击事件
document.getElementById('version-list').addEventListener('click', (e) => {
    const row = e.target.closest('tr');
    if (row) {
        const index = row.dataset.index;
        showVersionDetail(versions.value[index]);
    }
});

// 关闭弹窗
document.getElementById('modal-close').addEventListener('click', () => {
    document.getElementById('version-modal').style.display = 'none';
});

document.getElementById('version-modal').addEventListener('click', (e) => {
    if (e.target === document.getElementById('version-modal')) {
        document.getElementById('version-modal').style.display = 'none';
    }
});

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    const hash = window.location.hash.substring(1) || 'versions';
    switchPage(hash);
    document.querySelector(`[href="#${hash}"]`).classList.add('active');
    renderVersionList();
});

// 监听hash变化
window.addEventListener('hashchange', () => {
    const hash = window.location.hash.substring(1);
    switchPage(hash);
    document.querySelectorAll('.nav-button').forEach(btn => {
        btn.classList.remove('active');
        if (btn.getAttribute('href') === `#${hash}`) {
            btn.classList.add('active');
        }
    });
});

// 键盘事件
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' &&
        document.getElementById('version-modal').style.display === 'flex') {
        document.getElementById('version-modal').style.display = 'none';
    }
});

// 新增配置按钮点击事件
document.getElementById('config-files').addEventListener('click', () => {
    // 从DOM获取版本信息
    const detailContainer = document.getElementById('version-detail');
    const machineInfo = {
        name: document.querySelector('#version-detail .detail-item:nth-child(1) p').textContent,
        machineCode: document.querySelector('#version-detail .detail-item:nth-child(2) p').textContent,
        created: document.querySelector('#version-detail .detail-item:nth-child(3) p').textContent,
        creator: document.querySelector('#version-detail .detail-item:nth-child(4) p').textContent,
        id: detailContainer.querySelector('.detail-item').dataset.id
    };

    document.getElementById('file-manager-modal').style.display = 'block';
    document.body.style.overflow = 'hidden'; // 禁用背景滚动

    LoadDirectory(machineInfo);
});

document.getElementById('delete-version').addEventListener('click', async () => {
    alert("功能待开发")
    return

    // 获取版本ID（根据之前存储方式调整）
    const versionId = document.querySelector('#version-detail [data-id]')?.dataset.id;

    if (!versionId) {
        alert('未找到版本ID');
        return;
    }

    // 二次确认
    if (!confirm('确定要永久删除该版本吗？')) return;

    // 获取认证信息（根据实际存储方式调整）
    const token = localStorage.getItem('authToken');
    if (!token) AuthReDirection(false);

    try {
        const response = await fetch('/api/version/delete', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `${token}`,
            },
            body: JSON.stringify({
                id: versionId
            }),
        });

        const result = await response.json();

        if (result.code === '0') {
            alert('删除成功');
            document.getElementById('version-modal').style.display = 'none';
            // 刷新版本列表
            renderVersionList();
        } else {
            alert(`删除失败: ${result.message}`);
        }
    } catch (error) {
        console.error('删除请求失败:', error);
        alert('网络请求异常');
    }
});
